package com.jilefojing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jilefojing.beans.enums.PlatformEnum;
import com.jilefojing.beans.enums.PlatformEnumForPublish;
import com.jilefojing.beans.enums.StatusEnumForPublish;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.Banner;
import com.jilefojing.beans.pojos.base.BasePo;
import com.jilefojing.beans.pojos.enhanced.EnhancedBanner;
import com.jilefojing.beans.pojos.enhanced.EnhancedUser;
import com.jilefojing.beans.pojos.enhanced.base.BaseEnhanced;
import com.jilefojing.beans.query.BannerQuery;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.beans.vo.UploadFile;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.dao.IBannerDao;
import com.jilefojing.qiniu.beans.enums.BucketEnum;
import com.jilefojing.qiniu.beans.enums.BucketEnum.BucketEnumExtral_SourceEnum;
import com.jilefojing.service.IBannerService;
import com.jilefojing.service.IUserService;
import com.jilefojing.service.base.impl.BaseService;
import com.jilefojing.util.Detect;
import com.jilefojing.util.QiniuUtil;

/**
 * 
 * @author 作者 jgshun
 * @date 创建时间 2016年07月19日 13时23分08秒
 */
@Service
public class BannerService extends BaseService<Banner> implements IBannerService {
	@Autowired
	private IBannerDao bannerDao;
	@Autowired
	private IUserService userService;

	@Override
	public Pagination<EnhancedBanner> getPagination(BannerQuery bannerQuery, Pagination<EnhancedBanner> pagination, UserContext userContext) {
		@SuppressWarnings("unchecked")
		Pagination<Banner> bannerPagination = bannerDao.getPagination(bannerQuery, pagination.copy());
		pagination.setCount(bannerPagination.getCount());
		if (!Detect.notEmpty(bannerPagination.getItems())) {
			return pagination;
		}
		pagination.setItems(this.convent2Enhanceds(bannerPagination.getItems()));
		this.appendEnhancedCommons(pagination.getItems(), userContext);
		return pagination;
	}

	@Override
	public List<EnhancedBanner> appendEnhancedCommons(List<? extends BaseEnhanced> enhancedItems, UserContext userContext) {
		@SuppressWarnings("unchecked")
		List<EnhancedBanner> enhancedBanners = (List<EnhancedBanner>) enhancedItems;
		this.appendEnhancedUser(enhancedBanners, userContext);
		return enhancedBanners;
	}

	@Override
	public List<EnhancedBanner> appendEnhancedUser(List<EnhancedBanner> enhancedBanners, UserContext userContext) {
		List<Long> createUserIds = new ArrayList<Long>();
		for (EnhancedBanner _EnhancedBanner : enhancedBanners) {
			if (_EnhancedBanner.getEnhancedCreateUser() != null && _EnhancedBanner.getEnhancedCreateUser().getId() > 0) {
				createUserIds.add(_EnhancedBanner.getEnhancedCreateUser().getId());
			}
		}

		if (Detect.notEmpty(createUserIds)) {
			List<EnhancedUser> enhancedUsers = userService.getEnhancedUsers(createUserIds);
			if (Detect.notEmpty(enhancedUsers)) {
				for (EnhancedBanner _EnhancedBanner : enhancedBanners) {
					if (_EnhancedBanner.getEnhancedCreateUser() != null && _EnhancedBanner.getEnhancedCreateUser().getId() > 0) {
						for (EnhancedUser _EnhancedUser : enhancedUsers) {
							if (_EnhancedBanner.getEnhancedCreateUser().getId() == _EnhancedUser.getId()) {
								_EnhancedBanner.setEnhancedCreateUser(_EnhancedUser);
								break;
							}
						}
					}
				}
			}
		}

		return enhancedBanners;

	}

	@Override
	public List<EnhancedBanner> convent2Enhanceds(List<? extends BasePo> pos) {
		@SuppressWarnings("unchecked")
		List<Banner> banners = (List<Banner>) pos;

		List<EnhancedBanner> enhancedBanners = new ArrayList<EnhancedBanner>();
		for (Banner _Banner : banners) {
			if (Detect.notEmpty(_Banner.getCoverUrl()) && !_Banner.getCoverUrl().startsWith(SCHEMA)) {
				_Banner.setCoverUrl(QiniuUtil.getImagesDomain() + "/" + _Banner.getCoverUrl());
			}
			enhancedBanners.add(new EnhancedBanner(_Banner));
		}
		return enhancedBanners;
	}

	@Override
	public List<EnhancedBanner> getEnhanceds(List<Long> ids, UserContext userContext) {
		List<Banner> banners = bannerDao.getListByIds(ids);
		if (!Detect.notEmpty(banners)) {
			return null;
		}
		List<EnhancedBanner> enhancedBanners = this.convent2Enhanceds(banners);
		this.appendEnhancedCommons(enhancedBanners, userContext);
		return enhancedBanners;
	}

	@Override
	public Pagination<EnhancedBanner> getPaginationForActive(PlatformEnum platform, Pagination<EnhancedBanner> pagination, UserContext userContext) {
		if (!Detect.notEmpty(pagination.getOrders())) {
			pagination.addOrder(new Order(Banner.COLUMN_SORT, Order.ORDER_DESC));
		}

		List<PlatformEnumForPublish> platforms = new ArrayList<PlatformEnumForPublish>();
		platforms.add(PlatformEnumForPublish.ALL);
		if (platform == PlatformEnum.ANDROID) {
			platforms.add(PlatformEnumForPublish.ANDROID_AND_IOS);
			platforms.add(PlatformEnumForPublish.ANDROID);
		} else if (platform == PlatformEnum.IPHONE) {
			platforms.add(PlatformEnumForPublish.ANDROID_AND_IOS);
			platforms.add(PlatformEnumForPublish.IOS);
		} else if (platform == PlatformEnum.PC) {
			platforms.add(PlatformEnumForPublish.WEB_AND_WAP);
			platforms.add(PlatformEnumForPublish.WEB);
		} else if (platform == PlatformEnum.WAP) {
			platforms.add(PlatformEnumForPublish.WEB_AND_WAP);
			platforms.add(PlatformEnumForPublish.WAP);
		}

		BannerQuery bannerQuery = new BannerQuery();
		bannerQuery.setStatuses(Arrays.asList(new StatusEnumForPublish[] { StatusEnumForPublish.ALREADY_RELEASED }));
		bannerQuery.setPlatforms(platforms);
		Date nowDate = new Date();
		bannerQuery.setEqualAndAfterStartTime(nowDate);
		bannerQuery.setEqualAndBeforEndTime(nowDate);

		return this.getPagination(bannerQuery, pagination, userContext);
	}

	@Override
	public Banner update(Banner banner, UserContext userContext) throws UserContextException {
		StatusEnumForPublish status = StatusEnumForPublish.getStatusEnumByCode(banner.getStatus());
		PlatformEnumForPublish platform = PlatformEnumForPublish.getPlatformEnumByCode(banner.getPlatform());
		if (status == null) {
			throw new UserContextException("[未知状态]");
		}
		if (platform == null) {
			throw new UserContextException("[未知平台]");
		}

		Banner dbBanner = bannerDao.getById(banner.getId());
		if (dbBanner == null) {
			throw new UserContextException("[广告栏不存在]");
		}
		if (Detect.notEmpty(banner.getTitle())) {
			dbBanner.setTitle(banner.getTitle());
		}
		dbBanner.setSort(banner.getSort() == null ? 0 : banner.getSort());
		if (banner.getStartTime() != null) {
			dbBanner.setStartTime(banner.getStartTime());
		}
		if (banner.getEndTime() != null) {
			dbBanner.setEndTime(banner.getEndTime());
		}
		dbBanner.setUrl(banner.getUrl());
		dbBanner.setStatus(status.getCode());
		dbBanner.setPlatform(platform.getCode());
		dbBanner.setUpdateTime(new Date());

		return bannerDao.updateByPrimaryKey(dbBanner);
	}

	@Override
	public Banner add(Banner banner, UserContext userContext) throws UserContextException {
		if (!Detect.notEmpty(banner.getTitle())) {
			throw new UserContextException("[标题不能为空]");
		} else if (banner.getTitle().length() > 50) {
			throw new UserContextException("[标题不能超过50个字]");
		}

		if (banner.getStatus() == null || StatusEnumForPublish.getStatusEnumByCode(banner.getStatus()) == null) {
			throw new UserContextException("[状态未知/不能为空]");
		}

		if (banner.getPlatform() == null || PlatformEnumForPublish.getPlatformEnumByCode(banner.getPlatform()) == null) {
			throw new UserContextException("[平台未知/不能为空]");
		}
		if (!Detect.notEmpty(banner.getCoverUrl())) {
			throw new UserContextException("[封面不能为空]");
		}

		Date now = new Date();

		banner.setId(null);
		banner.setCreateTime(now);
		banner.setUpdateTime(now);
		if (banner.getSort() == null) {
			banner.setSort(0D);
		}
		if (banner.getStartTime() == null) {
			banner.setStartTime(now);
		}
		if (banner.getEndTime() == null) {
			banner.setEndTime(new GregorianCalendar(2999, 11, 31, 23, 59, 59).getTime());
		}
		banner.setCreateUser(userContext.getUserId());

		if (banner.getStartTime().after(banner.getEndTime())) {
			throw new UserContextException("[开始时间不能大于结束时间]");
		}

		return bannerDao.save(banner);
	}

	@Override
	public Banner updateCover(long id, UploadFile coverUploadFile, UserContext userContext) {
		Banner banner = bannerDao.getById(id);
		Date now = new Date();

		Detect.checkImgType(coverUploadFile.getSuffix());

		banner.setCoverUrl(QiniuUtil.upload(coverUploadFile, BucketEnum.IMG, BucketEnumExtral_SourceEnum.BANNER));
		banner.setUpdateTime(now);
		return bannerDao.updateByPrimaryKey(banner);
	}

	@Override
	public void delete(long id, UserContext userContext) throws UserContextException {
		Banner dbBanner = bannerDao.getById(id);
		if (dbBanner == null) {
			throw new UserContextException("[广告栏不存在]");
		}
		bannerDao.deleteById(id);
	}
}
